import axios from 'axios'
import NProgress from 'nprogress'
import config from './config'
import router from '@/router'
import store from '@/store'

import {
  Message
} from 'iview'
import { noLoadingUrl } from 'assets/scripts/common'

export default function $axios (options) {
  return new Promise((resolve, reject) => {
    const instance = axios.create({
      baseURL: config.baseURL
    })

    instance.defaults.withCredentials = true

    // request 拦截器
    instance.interceptors.request.use(config => {
      let token = localStorage.userToken

      // 多次调用的接口频繁出现 不出现loading
      if (!noLoadingUrl.includes(config.url) &&
        config.timeout !== 600000000 &&
        config.url.slice(0, 21) !== '/kg/visual/entity/get' &&
        config.url.slice(0, 26) !== '/kg/data/property/data/get' &&
        config.url.slice(0, 17) !== '/kg/visual/search') {
        store.commit('setAppSpinShow', true)
      }

      // 这里是一个hack，标识工作流，不启用全局loading而使用nprogress
      if (config.timeout === 600000000) {
        NProgress.start()
      }

      if (token) {
        config.headers.Authorization = token
      }
      return config
    })

    // response 拦截器
    instance.interceptors.response.use(
      response => {
        let data
        if (response.data === undefined) {
          data = JSON.parse(response.request.responseText)
        } else {
          data = response.data
        }

        // loading消除
        NProgress.done()
        store.commit('setAppSpinShow', false)

        // 根据返回的code值来做不同的处理
        let {
          retcode,
          desc
        } = data

        if (retcode === '000000') {
          delete data.retcode
          delete data.desc
          return data
        } else if (
          retcode === '200004' ||
          retcode === '200007' ||
          retcode === '200008' ||
          retcode === '999999' ||
          retcode === '401'
        ) {
          localStorage.clear();
          router.push({
            path: '/'
          })
          Message.error(desc || '请求出错')
        } else {
          Message.error(desc || '请求出错')
          return Promise.reject(desc) // 便于async 函数拦截错误
          // return false
        }
      },
      error => {
        NProgress.done()
        store.commit('setAppSpinShow', false)
        if (error.response) {
          let {
            status,
            data
          } = error.response
          let {
            desc
          } = data

          switch (status) {
            case 401:
              localStorage.clear();
              router.push({
                path: '/'
              })
              break;

            default:
              Message.error(desc || '请求出错')
          }
        } else {
          Message.error('请求出错')
        }
        return Promise.reject(error) // 返回接口返回的错误信息
      }
    )

    // 请求处理
    instance(options)
      .then(res => {
        resolve(res)
        return false
      })
      .catch(error => {
        // loading消除
        NProgress.done()
        store.commit('setAppSpinShow', false)
        reject(error)
      })
  })
}
